// StatusWindow.cpp : Implementation of CStatusWindow

#include "stdafx.h"
#include "StatusWindow.h"
#include "resource.h"
#include "rapiwrapper.h" 



//ListFilesRecursively -- Go through all files in directories and subdirectories
//recursively. start the accumulator with 0 before passing to this function to retrive
//the total file size of a folder. The BasicDir should NOT have the slash (\\) in the end of 
//the string.
void CStatusWindow::WorkOnFilesRecursively (TCHAR * basicDir,UINT64 *accumulator,bool bCopyFiles)
{
	WIN32_FIND_DATA findData;
	HANDLE findDataHANDLE = NULL;
	ZeroMemory(&findData,sizeof(findData));

	TCHAR bDir[MAX_PATH];

	_tcscpy(bDir,basicDir);
	_tcscat(bDir,_T("\\*.*"));
	
	findDataHANDLE = FindFirstFile(bDir,&findData);

	if (findDataHANDLE)
	{
		do
		{
			if (findData.cFileName[0]==_T('.')) continue;

			TCHAR fullPath[MAX_PATH];
			_tcscpy(fullPath,basicDir);
			_tcscat(fullPath,_T("\\"));
			_tcscat(fullPath,findData.cFileName);

			TCHAR relativePathOnDeviceT[MAX_PATH];
			if (bCopyFiles)
			{				
				//basicPathOnDesktop has the initial path;
				//fullPath has the current path
				//relative path is the m_szTarget+equals in both
				TCHAR * p;
				p = fullPath + _tcslen(basicPathOnDesktop);								

				OutputDebugString(_T("Basic dir is "));
				OutputDebugString(basicPathOnDesktop);
				OutputDebugString(_T("\n"));
				
				_tcscpy(relativePathOnDeviceT,m_szTarget);
				_tcscat(relativePathOnDeviceT,p);
				MSG(relativePathOnDeviceT);
			}

			if ((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY)				
			{
				if (bCopyFiles)
				{
#ifdef UNICODE					
					(*faCeCreateDirectory)(relativePathOnDeviceT,NULL);
#else
					WCHAR relativePathOnDeviceW[MAX_PATH];
					mbstowcs(relativePathOnDeviceW,relativePathOnDeviceT,MAX_PATH);
					(*faCeCreateDirectory)(relativePathOnDeviceW,NULL);
#endif
				}							
				
				WorkOnFilesRecursively(fullPath,accumulator,bCopyFiles);
			}
			else
			{
				if (bCopyFiles)
				{
					//Copy the file. The relativePath here gives me path+filename.
					//strip the filename out of it.

					TCHAR *  fileNameStrippedOut = _tcsrchr(relativePathOnDeviceT,_T('\\'));
					fileNameStrippedOut[0] = _T('\0');

					CopyFileToDevice(fullPath,relativePathOnDeviceT);
				}
				else
				{
					//Get the total file Size
					UINT64 totalFileSize = 0;
					totalFileSize = findData.nFileSizeHigh;
					totalFileSize = totalFileSize<<32;
					totalFileSize = totalFileSize | findData.nFileSizeLow;

					*accumulator+=totalFileSize;
				}
			}

		}
		while (FindNextFile(findDataHANDLE,&findData)==TRUE);
	}

	FindClose(findDataHANDLE);
		
}

void CStatusWindow::UpdateTotalProgressBar(DWORD moreBytesWritten)
{	
	FLOAT aux = 0;
	DWORD step=0;

	TotalBytesCopied+=moreBytesWritten;
	aux = (FLOAT) ((TotalBytesCopied)/(FLOAT)TotalFileSize);
	step=aux*100;
					
	::PostMessage(hwndTotalProgressBar,PBM_SETPOS,(WPARAM)step,0);
}


bool CStatusWindow::CopyFileToDevice(TCHAR * sourceFullPath, TCHAR * destinyFolder)
{
	OutputDebugString(_T("Copying: "));
	OutputDebugString(sourceFullPath);
	OutputDebugString(_T(" To "));
	OutputDebugString(destinyFolder);
	OutputDebugString(_T("\n"));

	
	if (!finishThread) //Avoid DeadLock 
	{
		HWND currentFileLabel = ::GetDlgItem(m_hWnd,IDC_CURRENTFILETTXT);
		::SetWindowText(currentFileLabel,sourceFullPath);
	}

	if ((GetFileAttributes(sourceFullPath) & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY)
	{
		//Ignore dirs.
		return false;		
	}

	if (sourceFullPath)
	{

		char buff[5006];
		HANDLE hSrc,hDest;
		DWORD dwSz, dwRes;
		TCHAR * filenameOnly;

		//finds the filename without the full path
		filenameOnly = _tcsrchr(sourceFullPath,_T('\\'));
		filenameOnly++;
		
		TCHAR dFullPath[MAX_PATH];
		_tcscpy(dFullPath,destinyFolder);
		
		//Hack--
		if (_tcscmp(dFullPath,_T("\\"))==0)
			_tcscpy(dFullPath,_T(""));

		_tcscat(dFullPath,_T("\\"));
		_tcscat(dFullPath,filenameOnly);

		
		//Opens the file in the desktop.
		hSrc = CreateFile( sourceFullPath,
						   GENERIC_READ,
						   FILE_SHARE_READ,
						   NULL,
						   OPEN_EXISTING,
						   0,
						   0);
#ifdef UNICODE		
		//Creates the file in the destiny
		hDest = (*faCeCreateFile)( destinyFolder, 
							  GENERIC_WRITE,
							  FILE_SHARE_READ | FILE_SHARE_WRITE,
							  NULL,
							  CREATE_ALWAYS,
							  0,
							  0);
#else

		WCHAR dFullPathW[MAX_PATH];
		mbstowcs(dFullPathW,dFullPath,MAX_PATH);

				//Creates the file in the destiny
		hDest = (*faCeCreateFile)( dFullPathW, 
							  GENERIC_WRITE,
							  FILE_SHARE_READ | FILE_SHARE_WRITE,
							  NULL,
							  CREATE_ALWAYS,
							  0,
							  0);
#endif


		if ((hSrc != INVALID_HANDLE_VALUE) &&
			 (hDest !=  INVALID_HANDLE_VALUE))
		{
			// Try to obtain hFile's size 
			DWORD dwSize = 	GetFileSize (hSrc,NULL); 

			if (dwSize<0)
			{
				MSG(_T("Could not detect the file size"));
			}
            					
			dwSz=5000;

			DWORD step=0;

			DWORD bytesCopied =0;
			DWORD oldstep = 0;
			DWORD bytesWritten=0;
			
			while (1) { 
				bytesWritten=0;

				if (finishThread)
				{
					MSG(_T("Forced to break in the middle of the while (1) loop"));	
					break;		
				}							
				
				ReadFile(hSrc, buff, dwSz, &dwRes, NULL);
				if (dwRes==0) break;
				(*faCeWriteFile)(hDest, buff, dwRes, &bytesWritten, NULL );
				if (dwRes!=bytesWritten) break;
										
				bytesCopied+=bytesWritten;						
				FLOAT aux = (FLOAT) ((FLOAT)bytesCopied/(FLOAT)dwSize);
				step=aux*100;
				
				if (hwndProgressBar)
					::PostMessage(hwndProgressBar,PBM_SETPOS,(WPARAM)step,0);	
				
				UpdateTotalProgressBar(bytesWritten);
				

				
			}

			//Delete the remainer
			if (finishThread)
			{
#ifdef UNICODE
				(*faCeDeleteFile)(dFullPath);
#else

				(*faCeDeleteFile)(dFullPathW);
#endif
			}
		}
		else
			::MessageBox(0,_T("Invalid handle value either at Host or Device"),_T("Error"),MB_OK);


		if (hDest)				
			(*faCeCloseHandle)(hDest);
		if (hSrc)				
			CloseHandle(hSrc);
		
	}
	else
	{
		MSG(_T("Could not detect the source filename"));
	}

}
//
////CeCopyFiles Thread - The core of the program
//DWORD WINAPI CECopyFilesThread(LPVOID args)
//{
//	//This function blocks if no device is connected or there is an error..
//	//Maybe an animation too
//
//	CStatusWindow * status = (CStatusWindow *)args;	
//
//	status->m_fIsWaitingConnection = true;		
//	
//	HRESULT hr = E_FAIL;
//
//	if (!RapiLoader())
//	{
//		MessageBox(0,_T("Could not Initialize RAPI. If you have Windows XP, please check if you have ActiveSync installed on your device" ),_T("Error"),MB_OK);
//		return -1;
//	}
//
//	if (status->finishThread==true) 
//	{
//		MSG(_T("The thread was forced to break!"));		
//		return -1;
//	}
//
//	//Will block here in most of the cases, so be aware.
//	hr = (*faCeRapiInit)();	
//
//	status->m_fIsWaitingConnection = false;
//
//	if (hr==E_FAIL)
//	{
//		MessageBox(0,_T("Error Trying to connect. The file(s) will not be copied"),_T("Error"),MB_OK);
//		//Prevent from copying
//		status->m_uNumFiles = 0;
//	}	
//
//	HWND hwndMainWindow = status->m_hWnd;
//
//	WIN32_FIND_DATA findData;
//	
//	//Get Total FileSize count before start copying, to know the MAX of the second progress bar (Total)
//
//
//	
//	for (unsigned int i=0;i<status->m_uNumFiles;i++)
//	{		
//		HANDLE hfile;
//		UINT64 combinedFileSize = 0;
//		hfile = FindFirstFile(status->m_szFile[i],&findData);
//		if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
//		{
//			ListFilesRecursively(status->m_szFile[i],&combinedFileSize,false);
//			MSG(_T("Directory!"));
//		}		
//		else
//		{
//			combinedFileSize = (UINT64)((UINT64)(findData.nFileSizeHigh<<32) | (UINT64)findData.nFileSizeLow);
//		}
//		status->TotalFileSize += combinedFileSize; 
//		FindClose(hfile);
//	}
//
//	ULARGE_INTEGER totalFreeSpaceOnDevice={0};
//	ULARGE_INTEGER dummyA,dummyB;
//
//	WCHAR szwTarget[MAX_PATH];
//
//	MultiByteToWideChar(CP_ACP, 0, status->m_szTarget, -1, szwTarget, MAX_PATH );
//	if ((TRUE==(*faCeGetDiskFreeSpaceEx)(szwTarget,&dummyA,&dummyB,&totalFreeSpaceOnDevice)))
//	{
//		if (totalFreeSpaceOnDevice.QuadPart<status->TotalFileSize)
//		{
//			MessageBox(0,_T("Not enough space in the target device. Please change your destination to a storage card or " \
//						  "free some space."),_T("Error"),MB_OK);
//
//
//			//Prevent from copying
//			status->m_uNumFiles = 0;
//		}
//	}
//	else
//	{
//		MessageBox(0,_T("Could not get the free space avaliable on the device."),_T("Error"),MB_OK);
//	}
//
//
//	if (status->hwndTotalProgressBar)
//	{
//		//::SendMessage(hwndTotalProgressBar,PBM_SETRANGE,0,MAKELPARAM(0,100));
//		//::SendMessage(hwndTotalProgressBar,PBM_SETSTEP,(WPARAM) (int)1,0);
//		::PostMessage(status->hwndTotalProgressBar,PBM_SETRANGE,0,MAKELPARAM(0,100));
//		::PostMessage(status->hwndTotalProgressBar,PBM_SETSTEP,(WPARAM) (int)1,0);
//
//	}
//
//
//	if (status->m_uNumFiles == 0)
//	{
//		MessageBox(0,_T("ERROR - The number of files is equal to 0!"),_T("Error"),MB_OK);
//	}
//
//	for (unsigned int i=0;i<status->m_uNumFiles;i++)
//	{
//		//Warning - there might be some leaks here
//		if (status->finishThread==true) 
//		{
//			MSG(_T("The thread was forced to break!"));
//			break;
//		}
//
//		OutputDebugString("Working...");
//		OutputDebugString( status->m_szFile[i] );
//		OutputDebugString("\n");
//		//is it a Folder?
//		if ((GetFileAttributes(status->m_szFile[i]) & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY)
//		{
//			MSG("Will recursively copy the dirs");
//			UINT64 dummy = 0;
//			ListFilesRecursively(status->m_szFile[i],&dummy,true);
//			//MessageBox(0, _T("Folder handling Not Implemented Yet"),_T("Error"),MB_OK);		
//			//TODO:Copy all files and subfolders to the selected target
//		}
//		else
//		{				
//			TCHAR * srcFileName; // = command->m_szFile[i];
//			//grab the filenameonly -- THIS DOESN`T CHECK FOR INVALID paths!
//			
//			int j = lstrlen(status->m_szFile[i]);
//			//find the srcFileName looking backwards to the first "\"
//			while (status->m_szFile[i][j]!=_T('\\'))
//			{
//				j--;
//			}
//			srcFileName = &(status->m_szFile[i][j+1]);
//
//			if (srcFileName)
//			{
//				HWND currentFileLabel = GetDlgItem(status->m_hWnd,IDC_CURRENTFILETTXT);
//
//				SetWindowText(currentFileLabel,status->m_szFile[i]);
//				
//				char dest[MAX_PATH];// = command->m_szTargets[command->currCommand];
//				WCHAR destW[MAX_PATH];
//				char buff[5006];
//				HANDLE hSrc,hDest;
//				DWORD dwSz, dwRes;
//				
//				//lstrcpy(dest,status->m_szTargets[status->currCommand]);
//				lstrcpy(dest,status->m_szTarget);
//
//				//Hack--
//				if (lstrcmp(dest,_T("\\"))==0)
//					lstrcpy(dest,_T(""));
//
//				lstrcat(dest,_T("\\"));
//				lstrcat(dest,srcFileName);				
//				
//				//TODO: this assumes it is a file...
//				//wprintf(_T("Copying %s to %s\n"),command->m_szFile[i], dest);
//				
//				hSrc = CreateFile( status->m_szFile[i],
//								   GENERIC_READ,
//								   FILE_SHARE_READ,
//								   NULL,
//								   OPEN_EXISTING,
//								   0,
//								   0);
//
//				MultiByteToWideChar(CP_ACP, 0, dest, -1, destW, MAX_PATH );
//
//				hDest = (*faCeCreateFile)( destW, 
//									  GENERIC_WRITE,
//									  FILE_SHARE_READ | FILE_SHARE_WRITE,
//									  NULL,
//									  CREATE_ALWAYS,
//									  0,
//									  0);
//
//				if ((hSrc != INVALID_HANDLE_VALUE) &&
//					 (hDest !=  INVALID_HANDLE_VALUE))
//				{
//					//TODO change this, this is slow!
//
//					// Try to obtain hFile's size 
//					DWORD dwSize = 	GetFileSize (hSrc,NULL); 
//
//					if (dwSize<=0)
//					{
//						MSG(_T("Could not detect the file size"));
//					}
//                    					
//					dwSz=5000;
//
//					DWORD step=0;
//
//					//::SendMessage(hwndProgressBar,PBM_SETRANGE,0,MAKELPARAM(0,100));
//					//::SendMessage(hwndProgressBar,PBM_SETSTEP,(WPARAM) (int)1,0);
//					::PostMessage(status->hwndProgressBar,PBM_SETRANGE,0,MAKELPARAM(0,100));
//					::PostMessage(status->hwndProgressBar,PBM_SETSTEP,(WPARAM) (int)1,0);
//					
//					DWORD bytesCopied =0;
//					DWORD oldstep = 0;
//					DWORD bytesWritten=0;
//					
//					while (1) { 
//						bytesWritten=0;
//
//						if (status->finishThread==true)
//						{
//							MSG(_T("Forced to break in the middle of the while (1) loop"));	
//							break;		
//						}
//										
//						
//						ReadFile(hSrc, buff, dwSz, &dwRes, NULL);
//						if (dwRes==0) break;
//						(*faCeWriteFile)(hDest, buff, dwRes, &bytesWritten, NULL );
//						if (dwRes!=bytesWritten) break;
//												
//						bytesCopied+=bytesWritten;						
//						FLOAT aux = (FLOAT) ((FLOAT)bytesCopied/(FLOAT)dwSize);
//						step=aux*100;
//						//::SendMessage(hwndProgressBar,PBM_SETPOS,(WPARAM)step,0);						
//						::PostMessage(status->hwndProgressBar,PBM_SETPOS,(WPARAM)step,0);						
//
//						status->TotalBytesCopied+=bytesWritten;
//						aux = (FLOAT) ((status->TotalBytesCopied)/(FLOAT)status->TotalFileSize);
//						step=aux*100;
//						//::SendMessage(hwndTotalProgressBar,PBM_SETPOS,(WPARAM)step,0);
//						::PostMessage(status->hwndTotalProgressBar,PBM_SETPOS,(WPARAM)step,0);
//						
//					}
//
//					//Delete the remainer
//					if (status->finishThread==true)
//					{
//						(*faCeDeleteFile)(destW);
//					}
//				}
//				else
//					MessageBox(0,_T("Invalid handle value either at Host or Device"),_T("Error"),MB_OK);
//
//
//				if (hDest)				
//					(*faCeCloseHandle)(hDest);
//				if (hSrc)				
//					CloseHandle(hSrc);
//				
//			}
//			else
//			{
//				MSG(_T("Could not detect the source filename"));
//			}
//			
//		}		
//		
//	}
//
//	if (false==status->finishThread)
//	{
//		status->m_cleanEnd = true;
//		MSG(_T("Sending WM_CLOSE from the thread"));
//		::PostMessage(hwndMainWindow,WM_CLOSE,0,0);	
//	}
//
//	MSG(_T("Thread Ended"));	
//
//	return 0;
//
//}
//



//CeCopyFiles Thread - The core of the program
DWORD WINAPI CECopyFilesThread(LPVOID args)
{
	//This function blocks if no device is connected or there is an error..
	//Maybe an animation too

	CStatusWindow * status = (CStatusWindow *)args;	

	//Setup the progress bar
	status->hwndProgressBar = GetDlgItem(status->m_hWnd,IDC_PROGRESS1);
	status->hwndTotalProgressBar = GetDlgItem(status->m_hWnd,IDC_TOTALPROGRESS);

	if (status->hwndProgressBar)
	{		
		::PostMessage(status->hwndProgressBar,PBM_SETRANGE,0,MAKELPARAM(0,100));
		::PostMessage(status->hwndProgressBar,PBM_SETSTEP,(WPARAM) (int)1,0);
		MSG(_T("hwndProgressBar was set."));
	}

	if (status->hwndTotalProgressBar)
	{		
		::PostMessage(status->hwndTotalProgressBar,PBM_SETRANGE,0,MAKELPARAM(0,100));
		::PostMessage(status->hwndTotalProgressBar,PBM_SETSTEP,(WPARAM) (int)1,0);
		MSG(_T("hwndTotalProgressBar was set."));
	}

	status->m_fIsWaitingConnection = true;		
	
	HRESULT hr = E_FAIL;

	if (!RapiLoader())
	{
		MessageBox(0,_T("Could not Initialize RAPI. If you have Windows XP/98/ME, please check if you have ActiveSync installed on your device" ),_T("Error"),MB_OK);
		return -1;
	}

	if (status->finishThread==true) 
	{
		MSG(_T("The thread was forced to break!"));		
		return -1;
	}

	//Will block here in most of the cases, so be aware.
	hr = (*faCeRapiInit)();	

	status->m_fIsWaitingConnection = false;

	if (hr==E_FAIL)
	{
		MessageBox(0,_T("Error Trying to connect. The file(s) will not be copied"),_T("Error"),MB_OK);
		//Prevent from copying
		status->m_uNumFiles = 0;
	}	

	HWND hwndMainWindow = status->m_hWnd;

	WIN32_FIND_DATA findData;



	//Get Total FileSize count before start copying, to know the MAX of the second progress bar (Total)
	
	for (unsigned int i=0;i<status->m_uNumFiles;i++)
	{		
		HANDLE hfile;
		UINT64 combinedFileSize = 0;
		hfile = FindFirstFile(status->m_szFile[i],&findData);
		if ((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY)
		{	
			MSG(_T("Directory!"));
			status->WorkOnFilesRecursively(status->m_szFile[i],&combinedFileSize,false);
			
		}		
		else
		{
			combinedFileSize = (UINT64)((UINT64)(findData.nFileSizeHigh<<32) | (UINT64)findData.nFileSizeLow);
		}
		status->TotalFileSize += combinedFileSize; 
		FindClose(hfile);
	}

	ULARGE_INTEGER totalFreeSpaceOnDevice={0};
	ULARGE_INTEGER dummyA,dummyB;

	WCHAR szwTarget[MAX_PATH];

	//MultiByteToWideChar(CP_ACP, 0, status->m_szTarget, -1, szwTarget, MAX_PATH );
	mbstowcs(szwTarget,status->m_szTarget,MAX_PATH);
	if ((TRUE==(*faCeGetDiskFreeSpaceEx)(szwTarget,&dummyA,&dummyB,&totalFreeSpaceOnDevice)))
	{
		if (totalFreeSpaceOnDevice.QuadPart<status->TotalFileSize)
		{
			MessageBox(0,_T("Not enough space in the target device. Please change your destination to a storage card or " \
						  "free some space."),_T("Error"),MB_OK);


			//Prevent from copying
			status->m_uNumFiles = 0;
		}
	}
	else
	{
		MessageBox(0,_T("Could not get the free space avaliable on the device."),_T("Error"),MB_OK);
	}

	if (status->m_uNumFiles == 0)
	{
		MessageBox(0,_T("ERROR - The number of files is equal to 0!"),_T("Error"),MB_OK);
	}

	for (unsigned int i=0;i<status->m_uNumFiles;i++)
	{		
		//Warning - there might be some leaks here
		if (status->finishThread==true) 
		{
			MSG(_T("The thread was forced to break!"));
			break;
		}

		OutputDebugString("Working...");
		OutputDebugString( status->m_szFile[i] );
		OutputDebugString("\n");
		//is it a Folder?
		if ((GetFileAttributes(status->m_szFile[i]) & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY)
		{
			MSG("Will recursively copy the dirs");
			UINT64 dummy = 0;

			_tcscpy(status->basicPathOnDesktop,status->m_szFile[i]);

			TCHAR * posofslash = _tcsrchr(status->basicPathOnDesktop,_T('\\'));
			

			//Create target dir
			TCHAR targetDir[MAX_PATH];

			_tcscpy(targetDir,status->m_szTarget);			
			_tcscat(targetDir,posofslash);

			OutputDebugString(_T("Create dir at "));
			OutputDebugString(targetDir);
			OutputDebugString(_T("\n"));

			//Will set the basicPathOnDesktop to the basic dir/
			posofslash[0] = _T('\0');
#ifdef UNICODE
			(*faCeCreateDirectory)(targetDir,NULL);
#else
			WCHAR targetDirW[MAX_PATH];
			mbstowcs(targetDirW,targetDir,MAX_PATH);
			(*faCeCreateDirectory)(targetDirW,NULL);			
#endif

			status->WorkOnFilesRecursively(status->m_szFile[i],&dummy,true);
			//MessageBox(0, _T("Folder handling Not Implemented Yet"),_T("Error"),MB_OK);		
			//TODO:Copy all files and subfolders to the selected target
		}
		else
		{
			status->CopyFileToDevice(status->m_szFile[i],status->m_szTarget);			
		}		
		
	}

	if (false==status->finishThread)
	{
		status->m_cleanEnd = true;
		MSG(_T("Sending WM_CLOSE from the thread"));
		::PostMessage(hwndMainWindow,WM_CLOSE,0,0);	
	}

	MSG(_T("Thread Ended"));	

	return 0;

}


// CStatusWindow implementation

void CStatusWindow::FreeNonWindowRelatedBlocks()
{	
	MSG(_T("FreeNonWindowRelatedBlocks()"));
	OutputDebugString(" Freeing m_szFile array\n");
	for (unsigned int i=0;i<m_uNumFiles;i++)
	if (m_szFile[i])
		{
			free(m_szFile[i]);
			m_szFile[i]=NULL;
		}

	if (m_szFile)
	{
		free(m_szFile);
		m_szFile=NULL;
	}
}

CStatusWindow::CStatusWindow(unsigned int uNumFiles)
{	
	m_cleanEnd=false;
	finishThread=false;
	m_uNumFiles = uNumFiles;
	m_szFile = (TCHAR **)malloc (uNumFiles*sizeof(TCHAR*));

	TotalBytesCopied=0;
	TotalFileSize=0;

	
}

void CStatusWindow::AddFileToQueue(TCHAR * lpszFile,unsigned int pos)
{	
	TCHAR msgbuff[MAX_PATH];
	sprintf(msgbuff,_T("Will try to add %s at position %d"),lpszFile,pos);
	MSG(msgbuff);

	//TODO: Investigate why this checkage was failing
	//if (m_szFile[pos])
	//{
		OutputDebugString("Adding ");
		OutputDebugString(lpszFile);
		OutputDebugString("\n");	
		m_szFile[pos] = (TCHAR *)malloc(sizeof(TCHAR)*lstrlen(lpszFile)+1*sizeof(TCHAR));
		lstrcpyn(m_szFile[pos],lpszFile,MAX_PATH);
	//}

}

//CStatusWindow::CStatusWindow(unsigned int uNumFiles,TCHAR ** szListOfFiles)
//		//: m_curFileProgressBar(0)
//{
//	m_uNumFiles = uNumFiles;
//	m_szFile = szListOfFiles;
//}
//
//This is not called when the window is created.
CStatusWindow::~CStatusWindow()
{	
	//MSG(_T("~CStatusWindow"));
	//FreeNonWindowRelatedBlocks();
}


LRESULT CStatusWindow::OnClose(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{	

	MSG(_T("CStatusWindow::OnClose"));
	finishThread = true;

	if ((true == m_fIsWaitingConnection) && faCeRapiUninit)
		(*faCeRapiUninit)(); //This will unblock our loop in the Thread if not connected	

	//Wait for the thread to end, if needed
	if (threadHandle && !m_cleanEnd)
	{
		MSG(_T("Waiting for thread to end"));
		WaitForSingleObject(threadHandle,10000);
		threadHandle=NULL;
	}

	FreeNonWindowRelatedBlocks();

	RapiUnloader();
	
	DestroyWindow();	
	return 0;
}


LRESULT CStatusWindow::OnInitDialog(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
	CAxDialogImpl<CStatusWindow>::OnInitDialog(uMsg, wParam, lParam, bHandled);	

	//HINSTANCE hInst = (HINSTANCE)GetModuleHandle(NULL); 
	////set our Icon
	//HICON hMyIcon = LoadIcon(hInst, MAKEINTRESOURCE(IDI_ICON1));
	////HICON hicon=::LoadResource(hInst,MAKEINTRESOURCE(IDI_ICON1));
	//if (hMyIcon)
	//	SetIcon(hMyIcon, FALSE); 

	//Init our values
	threadHandle=NULL;
	DWORD tid;

	//start the thread
	threadHandle = ::CreateThread(NULL, 
	         0,
			 CECopyFilesThread, //Function	
			 (LPVOID)this,
			 0, 
			 &tid); //thread identifier;
	return 1;  // Let the system set the focus
}

LRESULT CStatusWindow::OnClickedOK(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled)
{
	return 0;
}


LRESULT CStatusWindow::OnClickedCancel(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled)
{
	MSG(_T("OnClickedCancel"));
	::PostMessage(m_hWnd,WM_CLOSE,0,0);
	return 0;
}